
package com.zcp.pcsuitall.test;

import com.zcp.pcsuitall.MyDes;
import com.zcp.pcsuitall.PhoneServiceAllActivity;
import com.zcp.pcsuitall.XmlDataDealWith;
import com.zcp.pcsuitall.business.AppInfoObject;

import org.apache.http.util.EncodingUtils;
import org.xmlpull.v1.XmlPullParser;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.util.Log;
import android.util.Xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CommonUtil {

    private static String TAG = "CommonUtil";
    
    private static String cipherKey="asdfghjk";;
    
    /**
     * 启动activity服务。
     * @param context
     */
    public static void startActivity(Context context) {
        if (!Synchronous.isStart()) {
            stopActivity(context);
            Log.i("222", "startActivity");
            Intent intent = new Intent(context, PhoneServiceAllActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            // intent.putExtra("reStart", "true");
            context.startActivity(intent);
            try {
                // 等待服务启动，等待时间为3秒。
                Thread.sleep(3000);
            } catch (Exception e) {
            }

            // 重设一下密钥
            try {
                SocketChannel sc= CommonUtil.getChannel();

                String resetKey = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>ResetKey</action></root>";
                // 发送数据
                CommonUtil.sendData(sc, resetKey);
                String result = CommonUtil.writeDataToFile(sc);
                cipherKey = XmlDataDealWith.getRegularSingle("key", result);
                Log.i("222", "ResetKey=" + cipherKey);
                CommonUtil.closeChannel(sc);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Synchronous.setStart();
        }
        return;
    }
    
    /**
     * 停止activity服务。
     * @param context
     */
    public static void stopActivity(Context context) {
        Intent intent = new Intent("com.zcp.pcsuitall.phone.receiver.closeService");
        context.sendBroadcast(intent);
        try {
            // 等待服务停止，等待时间为3秒。
            Thread.sleep(3000);
        } catch (Exception e) {
        }
        Synchronous.setStop();
        Log.i("222", "stopActivity");
    }
    
    /**
     * 关闭通道。
     * 
     * @param sc
     * @return
     * @throws IOException
     */
    public static boolean closeChannel(SocketChannel sc) throws IOException {
        boolean success = false;
        try {
            
            String closeChannel = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root><action>ColseComm</action></root>";
            success=CommonUtil.sendData(sc, closeChannel);            
        } catch (Exception e) {
            Log.e(TAG, "closeChannel error " + e.getMessage());
            success=false;
        }
        return success;
    }
    
    
    /**
     * 返回一个通道。
     * @return
     * @throws IOException
     */
    public static SocketChannel getChannel() throws IOException {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8849);
        // 生成一个socketchannel
        SocketChannel sc = SocketChannel.open();
        // 连接到server
        sc.connect(addr);
        while (!sc.finishConnect())
            ;
        return sc;
    }   
    
    /**
     * 返回一个通道。
     * @return
     * @throws IOException
     */
    public static SocketChannel getReportChannel() throws IOException {
        InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8850);
        // 生成一个socketchannel
        SocketChannel sc = SocketChannel.open();
        // 连接到server
        sc.connect(addr);
        while (!sc.finishConnect())
            ;
        return sc;
    } 

    
    public static void closeActivity(Context context,String name)
    {
        Intent intent=new Intent("com.zcp.pcsuit.phone.receiver.closeService");
        intent.putExtra("name", name);
        context.sendBroadcast(intent);
    }
    
    
    /**
     * 发送数据。
     * 
     * @param sc
     * @param value
     */
    public static boolean sendData(SocketChannel sc, String value) {
        try {
            
            value=MyDes.encryptDES(value, cipherKey);
            ByteBuffer w_buff = ByteBuffer.allocate(value.length()*5);
            w_buff.clear();
            w_buff.put(value.getBytes());
            w_buff.flip();
            EchoToService(sc, w_buff);
            w_buff.clear();
            return true;
        } catch (IOException ioe) {
           ioe.printStackTrace();
            return false;
        }
    }

    public static void EchoToService(SocketChannel sc, ByteBuffer write_buff) throws IOException {
        while (write_buff.hasRemaining())
            sc.write(write_buff);
    }
    
//    /**
//     * 把通道中数据读取到文件流中。
//     * @param sc
//     * @param toFile
//     */
//    public  static String getDataFromChannel(SocketChannel sc) {
//        StringBuffer resultBuf = new StringBuffer();
//        ByteBuffer r_buff = ByteBuffer.allocate(1024);
//        try {
//            r_buff.clear();
//            String result = null;
//            int size = 0;   
//            while ((size=sc.read(r_buff)) > 0) {
//                // 确保r_buff可读
//                r_buff.flip();
//                result = new String(r_buff.array(),0,size);
//                resultBuf.append(result);
//                r_buff.clear();
//                if ((result.indexOf("</root>") != -1)||(resultBuf.toString().indexOf("</root>")!=-1)) {
//                    Log.i(TAG, "read data to file end");
//                    break;
//                }
//            }
//            
//            
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return resultBuf.toString();
//
//    }
    
    /**
     * 读取通道中数据，设置超时时间为6秒。
     * 
     * @param sc
     * @return
     */
    public static String writeDataToFile(final SocketChannel sc) {
        return writeDataToFile(sc, 12);
    }
    /**
     * 读取通道中数据，设置超时时间为second秒。
     * 
     * @param sc
     * @param second超时时间。
     * @return
     */
    public static String writeDataToFile(final SocketChannel sc,int second) {

        String result = null;
        ExecutorService executor = Executors.newSingleThreadExecutor();
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            public String call() {
                // 真正的任务在这里执行，这里的返回值类型为String，可以为任意类型
                return XmlDataDealWith.getDataFromChannel(sc,cipherKey);
            }
        });
        executor.execute(future);
        // 在这里可以做别的任何事情
        try {
            result = future.get(second, TimeUnit.SECONDS); // 取得结果，同时设置超时执行时间为6秒。同样可以用future.get()，不设置执行超时时间取得结果
        } catch (InterruptedException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (ExecutionException e) {
            e.printStackTrace();
            future.cancel(true);
        } catch (TimeoutException e) {
            e.printStackTrace();
            future.cancel(true);
        } finally {
            executor.shutdown();
        }
        return result;

    }
    
    
    
    /**
     * 分析文件流。<br>
     * 
     * @param inputStream
     * @return
     */
    public static LinkedList<AppInfoObject> analysisString(String value) {
        LinkedList<AppInfoObject> itemList = new LinkedList<AppInfoObject>();
        AppInfoObject item = null;
        try {
            InputStream inputStream = new ByteArrayInputStream(value.getBytes());
            XmlPullParser parser = Xml.newPullParser();    
            parser.setInput(inputStream, "UTF-8");
            int event = parser.getEventType();// 产生第一个事件
            String currentName = null;
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
                    	
                        currentName = parser.getName();
                        if ("item".equals(currentName)) {// 判断开始标签元素是否是action
                            item = new AppInfoObject(null, null, null, null, null,null,0);
                            // item.setName(parser.getAttributeValue("",
                            // "name"));
                            // item.setSize(parser.getAttributeValue("",
                            // "size"));

                        }
                        break;
                    case XmlPullParser.TEXT: {
                        if ("name".equals(currentName)) {
                            item.setName(parser.getText());
                        } else if ("size".equals(currentName)) {
                            item.setSizeStr(parser.getText());
                        } else if ("version".equals(currentName)) {
                            item.setVersion(parser.getText());
                        } else if ("ico".equals(currentName)) {
                            item.setIconStr(parser.getText());
                        } else if ("package".equals(currentName)) {
                            item.setPackageStr(parser.getText());
                        }else if ("apkPath".equals(currentName)) {
                            item.setSourcePath(parser.getText());
                        }else if ("isSysApk".equals(currentName)) {
                            item.setOther(parser.getText());
                        }
                        
                        
                        break;
                    }
                    case XmlPullParser.END_TAG: {
                        if ("item".equals(parser.getName())) {
                            itemList.add(item);
                        }
                        currentName = null;
                        break;

                    }

                }
                event = parser.next();// 进入下一个元素并触发相应事件
            }// end while

        } catch (Exception e) {
            e.printStackTrace();
        }
        return itemList;
    }  
    
    
    /**
     * 获取from,to,total数据。<br>
     * 
     * @param inputStream
     * @return
     */
    public static SizeObject getFromToTotalData(String value) {
        SizeObject sizeData = new SizeObject();
        try {
            InputStream inputStream = new ByteArrayInputStream(value.getBytes());
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");
            int event = parser.getEventType();// 产生第一个事件
            String currentName = null;
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
                        currentName = parser.getName();

                    case XmlPullParser.TEXT: {
                        if ("from".equals(currentName)) {
                            sizeData.setFrom(parser.getText());
                        } else if ("to".equals(currentName)) {
                            sizeData.setTo(parser.getText());
                        } else if ("total".equals(currentName)) {
                            sizeData.setTotal(parser.getText());
                        }
                        break;
                    }
                    case XmlPullParser.END_TAG: {
                        currentName = null;
                        break;

                    }

                }
                event = parser.next();// 进入下一个元素并触发相应事件
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return sizeData;
    }
    
    
    /**
     * 获取联系人id列表。<br>
     * 
     * @param inputStream
     * @return
     */
    public static LinkedList<String> getContactsId(String value) {
        return getContactsElement(value,"id",4);   
    }
    
    
    
    /**
     * 获取联系人图片列表。<br>
     * 
     * @param inputStream
     * @return
     */
    public static LinkedList<String> getContactsIcon(String value) {
        return getContactsElement(value,"photo",4);       
    }
    
    
    /**
     * 获取联系人图片列表。<br>
     * 
     * @param inputStream
     * @return
     */
    public static LinkedList<String> getContactsElement(String value,String element,int depth) {
        LinkedList<String> elements = new LinkedList<String>();
        try {
            InputStream inputStream = new ByteArrayInputStream(value.getBytes());
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");
            int event = parser.getEventType();// 产生第一个事件
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:
                        if (parser.isEmptyElementTag())
                            break;
                        if (element.equals(parser.getName()) && parser.getDepth() == depth) {
                            elements.add(parser.nextText());
                        }
                }
                event = parser.next();// 进入下一个元素并触发相应事件
            }

        } catch (Exception e) {
           e.printStackTrace();
        }
        return elements;
    }

    /**
     * 文件能正常被xml解析。<br>
     * 
     * @param value
     * @return
     */
    public static boolean checkCanBeenParse(String value) {
        boolean isCan = false;
        try {
            InputStream inputStream = new ByteArrayInputStream(value.getBytes());
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");
            int event = parser.getEventType();// 产生第一个事件
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_TAG:// 判断当前事件是否是标签元素开始事件
                        break;
                    case XmlPullParser.TEXT:
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();// 进入下一个元素并触发相应事件
            }// end while
            isCan = true;
        } catch (Exception e) {
              e.printStackTrace();
        }
        return isCan;
    }
    
  
    
    public static String getAssetsFile(Context context,String fileName)
    {
        String result=null;
        AssetManager am=context.getAssets();
        try {
            InputStream inputStream=am.open(fileName);
            
            int lenght=inputStream.available();            
            byte[] buffer=new byte[lenght];
            inputStream.read(buffer);
            inputStream.close();
            result=EncodingUtils.getString(buffer, "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;

    }

}
